/*
 * @Description:
 * @Author: lijiajin
 * @Date: 2020-07-06 10:42:47
 * @LastEditTime: 2020-07-10 12:05:54
 * @LastEditors: lijiajin
 */

/********************************************** 切换按钮 **********************************************/

$(function () {
    // 开关按钮
    var ajax_turn_btn_able = true;
    $(".ajax-turn-btn").on("change", function () {
        if (!ajax_turn_btn_able) {
            return;
        }
        var url = $(this).attr("data-url");
        var this_ = $(this);
        // TODO
        $.ajax({
            type: "POST",
            url: url,
            data: {value: this_.val()},
            dataType: "json",
            success: function (data) {
                if (data.status == 500) {
                    // 失败
                    showToast(data.msg, 2);
                    resetAjaxTurn(this_);
                }
            },
            error: function () {
                showToast("请求失败", 2);
                resetAjaxTurn(this_);
            },
            beforeSend: function () {
                ajax_turn_btn_able = false;
                showLoading();
            },
            complete: function () {
                ajax_turn_btn_able = true;
                hideLoading();
            }
        });
    })
})

/********************************************** 表单提交 **********************************************/

$(function () {
    // 表单提交
    var ajax_form_able = true;
    $(".ajax-form").on("click", ".ajax-form-commit", function () {
        if (!ajax_form_able) {
            return;
        }
        var form = $(this).closest("form.ajax-form");
        if (!checkForm(form)) {
            return;
        }
        var url = $(form).attr("action");
        var formData = new FormData($(form)[0]);
        // TODO
        $.ajax({
            type: "POST",
            url: url,
            contentType: false,
            processData: false,
            data: formData,
            dataType: "json",
            success: function (data) {
                if (data.status == 200) {
                    showToast("保存成功", 1);
                    if ($(form).hasClass(".ajax-form-dialog")) {
                        // 刷新父窗体
                        parent.location.reload();
                    }
                } else if (data.status == 400) {
                    showToast("保存失败", 2);
                    handleErrorList(data.msg);
                } else {
                    showToast(data.msg, 3);
                }
            },
            error: function () {
                showToast("请求失败", 2);

                // TODO  静态页测试 需删除  start
                console.log("静态页测试")
                var msg = {
                    "common": [
                        {"field": "aaa", "msg": "请输入aaa"},
                        {"field": "bbb", "msg": "请输入bbb"},
                    ],
                    "lang": {
                        "1": [
                            {"field": "ccc", "msg": "请输入ccc-0", index: 0},
                            {"field": "ccc", "msg": "请输入ccc-1", index: 1},
                        ],
                        "3": [
                            {"field": "ccc", "msg": "请输入ccc-2", index: 2},
                        ]
                    }
                }
                handleErrorList(msg);
                // TODO  静态页测试 需删除  end

            },
            beforeSend: function () {
                ajax_form_able = false;
                showLoading();
            },
            complete: function () {
                ajax_form_able = true;
                hideLoading();
            }
        });
    })

    $(".ajax-form,.ajax-form-dialog").find(".check-input").on("blur", function () {
        $(this).closest(".item-box").find(".m-error").remove();
        $(this).closest(".item-box").find(".red-border").removeClass("red-border");
        // $(".language-exchange").find("span").remove();
    })
    $(".ajax-form,.ajax-form-dialog").find(".check-select").on("change", function () {
        $(this).closest(".item-box").find(".m-error").remove();
        $(this).closest(".item-box").find(".red-border").removeClass("red-border");
        // $(".language-exchange").find("span").remove();
    })
})


// 处理错误信息
function handleErrorList(msg) {

    console.log("handleErrorList")

    if (isArrayFn(msg)) {
        console.log("msg array");
        console.log("msg——" + JSON.stringify(msg));

        for (var i = 0; i < msg.length; i++) {
            if (checkPositiveIntegerAndZero(msg[i].index)) {
                var item = $(".item-box.item-list .item." + msg[i].field).siblings(".item-title").siblings(".item")[msg[i].index];
                showMsg(msg[i].msg, $(item), $(item).find("input,textarea,select"));
            } else {
                showMsg(msg[i].msg, $(".item-box .item." + msg[i].field), $(".item-box .item." + msg[i].field).find("input,textarea,select"));
            }
        }
    } else {
        console.log("msg object");
        console.log("msg.lang——" + JSON.stringify(msg.lang));
        console.log("msg.common——" + JSON.stringify(msg.common));
        console.log("msg.customer——" + JSON.stringify(msg.customer));
        console.log("msg.contact——" + JSON.stringify(msg.contact));

        if (isArrayFn(msg.common)) {
            for (var m = 0; m < msg.common.length; m++) {
                if (checkPositiveIntegerAndZero(msg.common[m].index)) {
                    var item = $(".item-box.item-list .item." + msg.common[m].field).siblings(".item-title").siblings(".item")[msg.common[m].index];
                    showMsg(msg.common[m].msg, $(item), $(item).find("input,textarea,select"));
                } else {
                    showMsg(msg.common[m].msg, $(".item-box .item." + msg.common[m].field), $(".item-box .item." + msg.common[m].field).find("input,textarea,select"));
                }
            }
        }

        if (!isArrayFn(msg.lang)) {
            console.log("msg.lang")
            for (var n in msg.lang) {
                for (var nn = 0; nn < msg.lang[n].length; nn++) {
                    if (checkPositiveIntegerAndZero(msg.lang[n][nn].index)) {
                        var item = $(".item-box[data-translate='true'][data-id='" + n + "'] .item." + msg.lang[n][nn].field).siblings(".item-title").siblings(".item")[msg.lang[n][nn].index];
                        showMsg(msg.lang[n][nn].msg, $(item), $(item).find("input,textarea,select"));
                        checkSmallLanguagesTan($(item))
                    } else {
                        showMsg(msg.lang[n][nn].msg, $(".item-box[data-translate='true'][data-id='" + n + "'] .item." + msg.lang[n][nn].field), $(".item-box[data-translate='true'][data-id='" + n + "'] .item." + msg.lang[n][nn].field).find("input,textarea,select"));
                        checkSmallLanguagesTan($(".item-box[data-translate='true'][data-id='" + n + "'] .item." + msg.lang[n][nn].field))
                    }
                }
            }
        }

        if (isArrayFn(msg.customer)) {
            for (var f = 0; f < msg.customer.length; f++) {
                if (checkPositiveIntegerAndZero(msg.customer[f].index)) {
                    var item = $(".customer-error-box .item-box.item-list .item." + msg.customer[f].field).siblings(".item-title").siblings(".item")[msg.customer[f].index];
                    showMsg(msg.customer[f].msg, $(item), $(item).find("input,textarea,select"));
                } else {
                    showMsg(msg.customer[f].msg, $(".customer-error-box .item-box .item." + msg.customer[f].field), $(".item-box .item." + msg.customer[f].field).find("input,textarea,select"));
                }
            }
        }

        if (isArrayFn(msg.contact)) {
            for (var t = 0; t < msg.contact.length; t++) {
                if (checkPositiveIntegerAndZero(msg.contact[t].index)) {
                    var item = $(".contact-error-box .item-box.item-list .item." + msg.contact[t].field).siblings(".item-title").siblings(".item")[msg.contact[t].index];
                    showMsg(msg.contact[t].msg, $(item), $(item).find("input,textarea,select"));
                } else {
                    showMsg(msg.contact[t].msg, $(".contact-error-box .item-box .item." + msg.contact[t].field), $(".item-box .item." + msg.contact[t].field).find("input,textarea,select"));
                }
            }
        }
    }
}

// 表单验证
function checkForm(form) {
    $(form).find(".m-error").remove();
    $(form).find(".red-border").removeClass("red-border");
    $(".language-exchange").find("span").remove();
    var okAble = true;
    if (!checkInputText(form)) {
        okAble = false;
    }
    if (!checkSelectText(form)) {
        okAble = false;
    }
    if (!checkPicList(form)) {
        okAble = false;
    }
    if (!checkCheckboxNum(form)) {
        okAble = false;
    }
    if (!checkBannerPic(form)) {
        okAble = false;
    }

    return okAble;
}

// 验证输入框
function checkInputText(form) {
    var inputTextAble = true;
    $(form).find(".check-input").each(function (index, item) {

        $(item).val($.trim($(item).val())); // 去首位空格

        if ($(item).attr("data-empty") && !$(item).val()) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                showMsg($(item).attr("data-empty"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item);
            }
        }

        if ($(item).val() && $(item).attr("data-length") && $(item).val().length > parseInt($(item).attr("data-length"))) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                showMsg($(item).attr("data-lengthText"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item)
            }
        }

        if ($(item).val() && $(item).attr("data-lengthMin") && $(item).val().length < parseInt($(item).attr("data-lengthMin"))) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                showMsg($(item).attr("data-lengthMinText"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item)
            }
        }

        if ($(item).val() && $(item).attr("data-url") && !checkURL($(item).val())) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                if ($(item).closest(".item-cell-box-banner").length > 0) {
                    showMsg($(item).attr("data-url"), $(item), $(item));
                } else {
                    showMsg($(item).attr("data-url"), $(item).closest(".item"), $(item));
                }
                checkSmallLanguagesTan(item)
            }
        }

        if ($(item).val() && $(item).attr("data-email") && !checkEmail($(item).val())) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                showMsg($(item).attr("data-email"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item)
            }
        }

        if ($(item).val() && $(item).attr("data-phone11") && !checkPhone11($(item).val())) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                showMsg($(item).attr("data-phone11"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item)
            }
        }

        if ($(item).val() && $(item).attr("data-emails") && !checkEmails($(item).val())) {
            if (!$(item).hasClass(".red-border")) {
                inputTextAble = false;
                showMsg($(item).attr("data-emails"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item)
            }
        }

        if ($(item).val() && $(item).attr("data-limit")) {
            if (!$(item).hasClass(".red-border")) {
                if ($(item).attr("data-limit") == "nls" && !checknls($(item).val())) {
                    inputTextAble = false;
                    showMsg($(item).attr("data-limitText"), $(item).closest(".item"), $(item));
                    checkSmallLanguagesTan(item)
                } else if ($(item).attr("data-limit") == "ns" && !checkns($(item).val())) {
                    inputTextAble = false;
                    showMsg($(item).attr("data-limitText"), $(item).closest(".item"), $(item));
                    checkSmallLanguagesTan(item)
                } else if ($(item).attr("data-limit") == "n99" && !checkPositiveInteger3($(item).val())) {
                    inputTextAble = false;
                    showMsg($(item).attr("data-limitText"), $(item).closest(".item"), $(item));
                    checkSmallLanguagesTan(item)
                }
            }
        }

        if ($(item).val() && $(item).attr("data-repeat")) {
            if ($(item).val() != $("#" + $(item).attr("data-repeat")).val()) {
                if (!$(item).hasClass(".red-border")) {
                    inputTextAble = false;
                    showMsg($(item).attr("data-repeatText"), $(item).closest(".item"), $(item));
                    checkSmallLanguagesTan(item)
                }
            }
        }

        // 加减项重复
        if ($(item).val() && $(item).closest(".item-list").attr("data-repeat")) {
            if (!$(item).hasClass(".red-border")) {
                console.log("ddddddddddddddddddddddd")

                var div_box = $(item).closest(".item-list");
                console.log($(div_box).find(".check-input").length)

                $(item).closest(".item-box").find(".check-input").each(function (index2, item2) {
                    console.log("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa:" + index2)
                    console.log($(item2).closest(".item").siblings(".item").find(".check-input").length)
                    var item2_ = $(item2)
                    item2_.closest(".item").siblings(".item").find(".check-input").each(function (index3, item3) {

                        console.log("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb:" + index3);
                        if (item2_.val() == $(item3).val()) {
                            inputTextAble = false;
                            if (!$(item2_).hasClass("red-border")) {
                                showMsg(item2_.closest(".item-box").attr("data-repeat"), $(item2_).closest(".item"), $(item2_));
                                checkSmallLanguagesTan(item2_)
                            }
                        }
                    })
                })
            }
        }
    })
    return inputTextAble;
}

// 验证选择框
function checkSelectText(form) {
    var selectTextAble = true;
    $(form).find(".check-select").each(function (index, item) {
        if ($(item).attr("data-empty") && !$(item).val()) {
            if (!$(item).hasClass(".red-border")) {
                selectTextAble = false;
                showMsg($(item).attr("data-empty"), $(item).closest(".item"), $(item));
                checkSmallLanguagesTan(item)
            }
        }
    })
    return selectTextAble;
}

// 验证图片
function checkPicList(form) {
    var picListAble = true;
    $(form).find(".bank-pic-list").each(function (index, item) {
        if ($(item).attr("data-empty")) {
            if ($(item).find(".pic-item").not(".add-pic-btn").length < parseInt($(item).attr("data-minNum")) || $(item).find(".pic-item").not(".add-pic-btn").length > parseInt($(item).attr("data-maxNum"))) {
                picListAble = false;
                showMsg($(item).attr("data-empty"), $(item).closest(".item"));
                checkSmallLanguagesTan(item)
            }
        }
    })
    return picListAble;
}

// 验证多选必选数量
function checkCheckboxNum(form) {
    var checkCheckboxNumAble = true;
    $(form).find(".item-box[data-checkCheckbox='true']").each(function (index, item) {
        if ($(item).find("input[type='checkbox']:checked").length < parseInt($(item).attr("data-checkCheckboxNum"))) {
            checkCheckboxNumAble = false;
            showMsg($(item).attr("data-checkCheckboxText"), $(item).find(".item"));
            checkSmallLanguagesTan(item)
        }
    })
    return checkCheckboxNumAble;
}

// 验证banner图片
function checkBannerPic(form) {
    if ($(form).find(".add-banner-item-btn").length > 0) {
        var hasPic = false;
        if ($(".item-cell-box.item-cell-box-banner").length > 0) {
            $(".item-cell-box.item-cell-box-banner").each(function (index, item) {
                if ($(item).find("img").attr("src")) {
                    hasPic = true;
                }
            })
        }
        if (!hasPic) {
            showMsg($(".add-banner-item-btn").attr("data-empty"), $(".add-banner-item-btn"));
            if ($(".language-exchange").find("a:nth-child(1)").find("span").length <= 0) {
                $(".language-exchange").find("a:nth-child(1)").append("<span style='color: #ff0000;font-weight: bold;margin-left: 3px;'>!</span>")
            }
            return false;
        }
    }
    return true;
}

/********************************************** table **********************************************/

$(function () {
    // 删除
    var ajax_table_delete_able = true;
    $(".ajax-table-delete").on("click", function () {
        if (!ajax_table_delete_able) {
            return;
        }
        var title = $(this).attr("data-title") ? $(this).attr("data-title") : "确认删除";
        var text = $(this).attr("data-text") ? $(this).attr("data-text") : "删除后不可恢复，继续吗？";
        var url = $(this).attr("data-url");
        var this_ = $(this);
        var trs = [];
        var ids = [];
        var names = [];
        if (this_.hasClass("ajax-table-delete-all")) {
            if ($("table tbody").find("input[type='checkbox']:checked").length <= 0) {
                showToast("请至少选择一条数据，然后再操作", 3);
                return;
            }
            $("table tbody").find("input[type='checkbox']:checked").each(function (index, item) {
                ids.push($(item).val());
                names.push($(item).attr('data-name'));
                trs.push($(item).closest("tr"));
            })
        } else {
            ids.push(this_.attr("data-id"));
            names.push(this_.attr("data-name"));
            trs.push(this_.closest("tr"));
        }

        layer.open({
            title: title,
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box'><p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p><p class='text'>" + text + "</p></div>",
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                // TODO
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {"ids[]": ids, "name[]" : names},
                    dataType: "json",
                    success: function (data) {
                        if (data.code == 200) {
                            // 成功
                            showToast(data.msg, 1);
                            $(trs).each(function (index, item) {
                                $(item).remove();
                            })
                        } else {
                            // 失败
                            showToast(data.msg, 2);
                        }
                    },
                    error: function () {
                        showToast("请求失败", 2);
                    },
                    beforeSend: function () {
                        ajax_table_delete_able = false;
                        showLoading();
                    },
                    complete: function () {
                        ajax_table_delete_able = true;
                        hideLoading();
                    }
                });
                layer.close(index)
            }
        });

    })

    // 排序
    var ajax_table_paixu = true;
    $(".ajax-table-paixu").on("click", function () {
        if (!ajax_table_paixu) {
            return;
        }
        var url = $(this).attr("data-url");
        var list_orders = [];

        $("table tbody").find("input[type='text'].table-paixu-input").each(function (index, item) {
            var data = {};
            data.list_order = $(item).val();
            data.id = $(item).attr("data-id");
            list_orders.push(data);
        })

        // TODO
        $.ajax({
            type: "POST",
            url: url,
            data: {list_orders:list_orders},
            dataType: "json",
            success: function (data) {
                if (data.code == 200) {
                    // 成功
                    showToast(data.msg, 1, 3);

                } else {
                    // 失败
                    showToast(data.msg, 2);
                }
            },
            error: function () {
                showToast("请求失败", 2);
            },
            beforeSend: function () {
                ajax_table_paixu = false;
                showLoading();
            },
            complete: function () {
                ajax_table_paixu = true;
                hideLoading();
            }
        });

    })

})

/********************************************** 图片银行 **********************************************/

$(function () {
    // 删除
    var ajax_bank_delete_btn_able = true;
    $(".wrap-bank-pic-page").on("click", ".ajax-bank-delete-btn", function () {
        if (!ajax_bank_delete_btn_able) {
            return;
        }
        var title = $(this).attr("data-title") ? $(this).attr("data-title") : "确认删除";
        var text = $(this).attr("data-text") ? $(this).attr("data-text") : "删除后不可恢复，继续吗？";
        var url = $(this).attr("data-url");
        var ids = [];
        var $li = $(".wrap-bank-pic-page ul#img_bank_box li.selected");
        if ($li.length <= 0) {
            showToast("请至少选择一张图片", 3);
            return;
        }
        layer.open({
            title: title,
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box'><p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p><p class='text'>" + text + "</p></div>",
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                $li.each(function (index, item) {
                    ids.push($(item).attr("data-id"));
                })
                // TODO
                $.ajax({
                    type: "POST",
                    url: url,
                    data: ids,
                    dataType: "json",
                    success: function (data) {
                        if (data.status == 200) {

                        } else {

                        }
                    },
                    error: function () {
                        showToast("请求失败", 2);
                    },
                    beforeSend: function () {
                        ajax_bank_delete_btn_able = false;
                        showLoading();
                    },
                    complete: function () {
                        ajax_bank_delete_btn_able = true;
                        hideLoading();
                    }
                });
                layer.close(index)
            }
        });
    })

    // 移动分组
    var ajax_bank_move_group_able = true;
    $(".wrap-bank-pic-page").on("click", ".ajax-bank-move-group-btn", function () {
        if (!ajax_bank_move_group_able) {
            return;
        }
        var title = $(this).attr("data-title");
        var url = $(this).attr("data-url");
        var ids = [];
        var $li = $(".wrap-bank-pic-page ul#img_bank_box li.selected");
        if ($li.length <= 0) {
            showToast("请至少选择一张图片", 3);
            return;
        }
        layer.open({
            title: title,
            type: 2,
            skin: "layer-miframe layer-move-dialog",
            content: "file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/pic-bank-page-move-group-dialog.html",
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                $li.each(function (index, item) {
                    ids.push($(item).attr("data-id"));
                })
                var body = layer.getChildFrame('body', index);
                var select = body.find(".selext-box").find("select");
                var value = $(select).val();
                if (!value) {
                    showToast("请选择分组名称", 3);
                    return;
                }
                // TODO
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {ids: ids, value: value},
                    dataType: "json",
                    success: function (data) {
                        if (data.status == 200) {
                            showToast("保存成功", 1);
                        } else {
                            showToast("保存失败", 2);
                        }
                    },
                    error: function () {
                        showToast("请求失败", 2);
                    },
                    beforeSend: function () {
                        ajax_bank_move_group_able = false;
                        showLoading();
                    },
                    complete: function () {
                        ajax_bank_move_group_able = true;
                        hideLoading();
                    }
                });
                layer.close(index)
            }
        });
    })

    // 添加分组
    var ajax_bank_add_group_able = true;
    $(".wrap-bank-pic-page").on("click", ".ajax-bank-add-group-btn", function () {
        if (!ajax_bank_add_group_able) {
            return;
        }
        var title = $(this).attr("data-title");
        var url = $(this).attr("data-url");
        layer.open({
            title: title,
            type: 2,
            skin: "layer-miframe layer-move-dialog",
            content: "file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/pic-bank-page-add-group-dialog.html",
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var input = body.find(".selext-box").find("input");
                var value = $(input).val();
                if (!value) {
                    showToast("请输入分组名称", 3);
                    return;
                }
                // TODO
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {value: value},
                    dataType: "json",
                    success: function (data) {
                        if (data.status == 200) {
                            showToast("保存成功", 1);
                        } else {

                            showToast("保存失败", 2);
                        }
                    },
                    error: function () {
                        showToast("请求失败", 2);
                    },
                    beforeSend: function () {
                        ajax_bank_add_group_able = false;
                        showLoading();
                    },
                    complete: function () {
                        ajax_bank_add_group_able = true;
                        hideLoading();
                    }
                });
                layer.close(index)
            }
        });
    })

    // 更新水印
    var ajax_bank_watermark_refresh_able = true;
    $(".wrap-bank-pic-page").on("click", ".ajax-bank-watermark-refresh", function () {
        if (!ajax_bank_watermark_refresh_able) {
            return;
        }
        var url = $(this).attr("data-url");
        var ids = [];
        var $li = $(".wrap-bank-pic-page ul#img_bank_box li.selected");
        if ($li.length <= 0) {
            showToast("请至少选择一张图片", 3);
            return;
        }
        $li.each(function (index, item) {
            ids.push($(item).attr("data-id"));
        })
        // TODO
        $.ajax({
            type: "POST",
            url: url,
            data: {ids: ids},
            dataType: "json",
            success: function (data) {
                if (data.status == 200) {

                    // 打开进度条弹框
                    showInfoDialog("更新中...", "批量更新水印", 2);
                    // 修改进度条进度
                    $(".layer-info-dialog .box .percent-line span").css("width", "50%");

                    // 打开更新结果
                    showToast("更新成功", 1);
                    // showToast("更新完成<br/> 第1、2、6张更新失败",3);
                    // showToast("更新失败",2);

                } else {

                }
            },
            error: function () {
                showToast("请求失败", 2);
            },
            beforeSend: function () {
                ajax_bank_watermark_refresh_able = false;
                showLoading();
            },
            complete: function () {
                ajax_bank_watermark_refresh_able = true;
                hideLoading();
            }
        });
    })

})


/********************************************** 公共方法 **********************************************/

// 翻译弹窗
$(function () {

    // 翻译弹窗

    $(".wrap-box").on("click", ".ajax-form-translate", function () {
        var num = $(this).attr("data-translateNum") ? $(this).attr("data-translateNum") : "0";
        var title = $(this).attr("data-title") ? $(this).attr("data-title") : "翻译<span>（剩余字符数" + num + "）</span>";
        var form = $(this).closest("ajax-form");

        layer.open({
            title: title,
            type: 2,
            skin: "layer-miframe layer-translate-dialog",
            content: "file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/common-translate-dialog.html",
            btn: ['翻译', '取消'],
            yes: function (index, layero) {
                if (!ajax_form_translate_btn_able) {
                    return;
                }
                var body = layer.getChildFrame('body', index);
                var languageCheckList = $(body).find(".top").find("input[type='checkbox']:checked");
                var contentCheckList = $(body).find("table tbody").find("input[type='checkbox']:checked");
                if ($(languageCheckList).length <= 0) {
                    showToast("请选择翻译语言", 3);
                    return;
                }
                if ($(contentCheckList).length <= 0) {
                    showToast("请选择翻译内容", 3);
                    return;
                }
                var lIds = [];
                var datas = {
                    num: languageCheckList.length, // 语言个数
                    type: 1, // 1: 翻译中   2、翻译完成
                    list: []
                }
                $(languageCheckList).each(function (key, item) {
                    lIds.push($(item).val());
                    var item = {
                        status: key == 0 ? "ing" : "wait", // wait: 等待  ing：翻译中  success：翻译成功  fail: 翻译失败
                        language: $(item).parent("a").siblings(".text").html(),
                        text: key == 0 ? "翻译中..." : "等待" // 等待、翻译中...、翻译成功、翻译失败
                    }
                    datas.list.push(item);
                })
                var cIds = [];
                $(contentCheckList).each(function (key, item) {
                    cIds.push($(item).val());
                })
                var formData = {cIds: cIds, lIds: lIds}
                var mainLanguageId = $(".language-exchange").find("a:first-of-type").attr("data-id");

                var listHtml = ``;
                for (var i = 0; i < datas.list.length; i++) {
                    listHtml = listHtml + `<li class="${datas.list[i].status}"><span>${datas.list[i].language}</span><span>${datas.list[i].text}</span></li>`
                }
                var noNumHtml = "<div class='box'>" +
                    "<div id='page_loading'></div>" +
                    "<p class='img'><i class='icon iconfont icon3chenggong'></i></p>" +
                    "<p class='text'>翻译中...</p>" +
                    "<p class='text2'>翻译完成！</p>" +
                    "<p class='line'></p>" +
                    "<ul class='list'>" +
                    listHtml +
                    "</ul>" +
                    "</div>";
                ajax_form_translate_btn_able = false;
                layer.open({
                    title: " ",
                    type: 1,
                    btnAlign: 'c',
                    shadeClose: false,
                    skin: "layer-translating-dialog",
                    content: noNumHtml,
                    btn: ['继续翻译', '关闭'],
                    success: function (layero, index) {
                        $(function () {
                            showPageLoading2();
                        })
                        // 开始翻译
                        translateForm(form, formData, mainLanguageId, index, 0);
                    },
                    btn2: function (layero, index) {
                        console.log("btn2")
                        layer.closeAll()
                    }
                });
                return false;


            }
        });
    })
})


/**
 *
 * @param form  表单
 * @param formData 表单数据
 * @param mainLanguageId 主语种id
 * @param translatingDialog 翻译中弹窗
 * @param currentNum 当前要翻译第几个语种
 */
var ajax_form_translate_btn_able = true;

function translateForm(form, formData, mainLanguageId, translatingDialog, currentNum) {
    // TODO
    $.ajax({
        type: "POST",
        url: $(form).attr("action"),
        data: {
            lIds: formData.lIds,
            cIds: formData.cIds,
            mainLanguageId: mainLanguageId,
            translateNum: formData.lIds.length,
            currentLId: formData.lIds[currentNum]
        },
        dataType: "json",
        success: function (data) {
            console.log("success")
            if (data.status == 200) { // 成功
                $(".layer-translating-dialog").find(".list li:nth-child(" + (currentNum + 1) + ")").addClass("success").find("span:nth-child(2)").html("翻译成功");
                var datas2 = [
                    {
                        id: 1,
                        content: "我是翻译",
                        filed: "",
                        index: 0
                    }
                ]
                for (var i = 0; i < datas2.length; i++) {
                    if (checkPositiveIntegerAndZero(datas2[i].index)) {
                        var item = $(".item-box.item-list .item." + datas2[i].field).siblings(".item-title").siblings(".item")[datas2[i].index];
                        $(item).find(".check-input").val(datas2[i].content);
                    } else {
                        $(".item-box .item." + datas2[i].field).find(".check-input").val(datas2[i].content)
                    }
                }
            } else if (data.status == 201) { // 翻译失败
                $(".layer-translating-dialog").find(".list li:nth-child(" + (currentNum + 1) + ")").addClass("fail").find("span:nth-child(2)").html("翻译失败");
            } else if (data.status == 202) { // 翻译字数不够
                layer.close(translatingDialog);
                var noNumHtml = "<div class='box'>" +
                    "<p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p>" +
                    "<p class='text'>翻译字符超出剩余字符数，请购买字符后再翻译</p>" +
                    "</div>";
                layer.open({
                    title: " ",
                    type: 1,
                    btnAlign: 'c',
                    shadeClose: false,
                    skin: "layer-translating-nonum-dialog",
                    content: noNumHtml,
                    btn: ['关闭']
                });
                return false;
            } else {
                showToast(data.msg, 3);
                return false;
            }

            // 判断是否继续翻译
            if (currentNum + 1 >= formData.lIds.length) {
                $(".layer-translating-dialog").find(".box").addClass("complete");
                $(".layer-translating-dialog").find(".layui-layer-btn").show();
            } else {
                $(".layer-translating-dialog").find(".list li:nth-child(" + (currentNum + 2) + ")").addClass("ing").find("span:nth-child(2)").html("翻译中...");
                translateForm(form, formData, mainLanguageId, translatingDialog, currentNum + 1);
            }
        },
        error: function () {
            // console.log("error")
        },
        beforeSend: function () {
            ajax_form_translate_btn_able = false;
        },
        complete: function () {
            ajax_form_translate_btn_able = true;
        }
    });
}


$(function () {
    // 删除
    var ajax_list_delete_btn_able = true;
    $(".wrap-box").on("click", ".ajax-list-delete-btn", function () {
        if (!ajax_list_delete_btn_able) {
            return;
        }
        var id = $(this).attr("data-id");
        var url = $(this).attr("data-url");
        var parent = $(this).closest($(this).attr("data-parent"));
        var title = $(this).attr("data-title") ? $(this).attr("data-title") : "确认删除";
        var text = $(this).attr("data-text") ? $(this).attr("data-text") : "删除后不可恢复，继续吗？";
        layer.open({
            title: title,
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box'><p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p><p class='text'>" + text + "</p></div>",
            btn: ['确认', '取消'],
            yes: function (index, layero) {
                // TODO
                $.ajax({
                    type: "POST",
                    url: url,
                    data: {id: id},
                    dataType: "json",
                    success: function (data) {
                        if (data.status == 200) {
                            $(parent).remove(); // 删除
                        } else {

                        }
                    },
                    error: function () {
                        showToast("请求失败", 2);
                    },
                    beforeSend: function () {
                        ajax_list_delete_btn_able = false;
                        showLoading();
                    },
                    complete: function () {
                        ajax_list_delete_btn_able = true;
                        hideLoading();
                    }
                });
                layer.close(index)
            }
        });
    })

})


/**
 * 提示弹框
 * @param msg
 * @param title
 * @param type 1：提示信息   2：更新进度   3：更新进度完成情况  4: 翻译弹窗字数不够提示
 */
function showInfoDialog(msg, title, type) {
    if (!layer) return;
    if (!arguments[1]) title = "提示信息";
    if (!arguments[2]) type = 1;
    if (type == 1) {
        layer.open({
            title: title,
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box'><p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p><p class='text'>" + msg + "</p></div>",
            btn: ['确认', '取消']
        });
    } else if (type == 2) {
        layer.open({
            title: title,
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box box-line'><p class='text'>" + msg + "</p><p class='percent-line'><span></span></p></div>",
            btn: ['取消']
        });
    } else if (type == 3) {
        layer.open({
            title: "更新提示",
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box box-msg'><p class='result'></p><p class='error'></p></div>",
        });
    } else if (type == 4) {
        layer.open({
            title: title,
            type: 1,
            skin: "layer-info-dialog",
            content: "<div class='box'><p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p><p class='text'>" + msg + "</p></div>",
            btn: ['关闭']
        });
    }
}

// 语种叹号
function checkSmallLanguagesTan(item) {
    if (!$(item).closest(".item-box").attr("data-id") && $(".language-exchange").find("a:nth-child(1)").find("span").length <= 0) {
        $(".language-exchange").find("a:nth-child(1)").append("<span style='color: #ff0000;font-weight: bold;margin-left: 3px;'>!</span>")
    } else if ($(".language-exchange").find("a[data-id='" + $(item).closest(".item-box").attr("data-id") + "']").find("span").length <= 0) {
        $(".language-exchange").find("a[data-id='" + $(item).closest(".item-box").attr("data-id") + "']").append("<span style='color: #ff0000;font-weight: bold;margin-left: 3px;'>!</span>")
    }
}

// 是否为数组
function isArrayFn(value) {
    if (typeof Array.isArray === "function") {
        return Array.isArray(value);
    } else {
        return Object.prototype.toString.call(value) === "[object Array]";
    }
}

// 重置ajax请求失败的切换按钮，恢复到点击之前状态
function resetAjaxTurn(obj) {
    if ($(obj).prop("checked")) {
        $(obj).prop("checked", false);
        $(obj).closest(".icon").addClass("iconswitch-off").removeClass("iconkaiguananniu-kai");
    } else {
        $(obj).prop("checked", true);
        $(obj).closest(".icon").addClass("iconkaiguananniu-kai").removeClass("iconswitch-off");
    }
}


/********************************************** 其他 **********************************************/

$(function () {
    // 添加、编辑客服账号
    $(".wrap-box").on("click", ".ajax-setting-kefu-add-btn,.ajax-setting-kefu-edit-btn", function () {
        console.log("粥铺")
        var title = $(this).attr("data-title") ? $(this).attr("data-title") : "编辑客服";
        var id = $(this).attr("data-id") ? $(this).attr("data-id") : "-1";
        layer.open({
            title: title,
            type: 2,
            skin: "layer-miframe layer-kefu-dialog",
            content: "file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/setting-kefu-account-add-dialog.html",
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var btn = $(body).find(".ajax-form-commit");
                $(btn).click();
            }
        });
    })

    // seo优化-seo设置-单条编辑
    $(".wrap-box").on("click", ".ajax-table-seo-edit", function () {
        var id = $(this).closest("tr").find("input[type='checkbox']").val();
        layer.open({
            title: "编辑SEO",
            type: 2,
            skin: "layer-miframe layer-kefu-dialog",
            content: "file:///F:/web-project/%E5%93%8D%E8%B4%9D/%E5%90%8E%E5%8F%B0/XBMemberWeb/seo-youhua-set-edit-dialog.html",
            btn: ['保存', '取消'],
            yes: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                var btn = $(body).find(".ajax-form-commit");
                $(btn).click();
            }
        });
    })
})

// 确认使用模板弹窗
function confirmUseDialog(obj) {
    var form = $(obj).closest("form");
    layer.open({
        title: "选用模板",
        type: 1,
        skin: "layer-info-dialog",
        content: "<div class='box'><p class='img'><i class='icon iconfont icon4zhuyi-01'></i></p><p class='text'>确定要使用此模板吗？</p></div>",
        btn: ['确认', '取消'],
        yes: function (index, layero) {
            $(form).submit();
            layer.close(index);
        }
    });
}








